/**
 * 
 */
package fr.afcepf.atod.projet.services.implementations;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import fr.afcepf.atod.projet.entities.Cour;
import fr.afcepf.atod.projet.services.interfaces.IServiceCours;

/**
 * @author Administrator
 *
 */

@Service
@Transactional
public class ServiceCours implements IServiceCours {

	@PersistenceContext(unitName="myPersistenceUnit")
	private EntityManager entityManager;
	
	
	/* (non-Javadoc)
	 * @see fr.afcepf.atod.projet.services.interfaces.IServiceCours#ajouter(fr.afcepf.atod.projet.entities.Cour)
	 */
	@Override
	public Boolean ajouter(Cour c) {
		Boolean retour = false;
		try {
			entityManager.persist(c);
			retour = true;
		} catch (Exception e) {
			retour = false;
			e.printStackTrace();
		}
		return retour;
	}

	/* (non-Javadoc)
	 * @see fr.afcepf.atod.projet.services.interfaces.IServiceCours#editer(fr.afcepf.atod.projet.entities.Cour)
	 */
	@Override
	public Boolean editer(Cour c) {
		entityManager.merge(c);
		return true;
	}

	/* (non-Javadoc)
	 * @see fr.afcepf.atod.projet.services.interfaces.IServiceCours#getCourbyId(java.lang.Integer)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Cour getCourbyId(Integer id) {
		Query query = entityManager.createQuery("" + 
				"select c from Cour c where c.id=?");
		query.setParameter(1, id);
		List<Cour> listeCours = query.getResultList();
		Cour result = null;
		if(listeCours.size() >0)
			result = listeCours.get(0);
		return result;
	}

	/* (non-Javadoc)
	 * @see fr.afcepf.atod.projet.services.interfaces.IServiceCours#rechercherCours(fr.afcepf.atod.projet.entities.Cour)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Cour> rechercherCours(Cour c) {
		Query query = entityManager.createQuery("" +
		"select c from Cour c where c.intitule=?");
		query.setParameter(1, c.getIntitule());
		return query.getResultList();
	}

	/* (non-Javadoc)
	 * @see fr.afcepf.atod.projet.services.interfaces.IServiceCours#retirer(java.lang.Integer)
	 */
	@Override
	public Boolean retirer(Integer id) {
		entityManager.remove(this.getCourbyId(id));
		return true;
	}

}
